﻿using Common.Net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Joz.Web.Models
{
    public class FaceSetHelper
    {
        //face++ api_key
        static string api_key = ConfigurationManager.AppSettings["FaceApiKey"];
        //face++ api_secret
        static string api_secret = ConfigurationManager.AppSettings["FaceApiSecret"];

        /// <summary>
        /// 创建一个FaceSet集合
        /// </summary>
        /// <param name="display_name">FaceSet名称</param>
        public static string CreateFaceSet(string display_name)
        {
            try
            {
                string content = string.Empty;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://api-cn.faceplusplus.com/facepp/v3/faceset/create");
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36";
                myRequest.Method = "POST";
                myRequest.ContentLength = 0;

                Dictionary<string, string> datas = new Dictionary<string, string>();
                datas.Add("api_key", api_key);
                datas.Add("api_secret", api_secret);
                datas.Add("display_name", display_name);
                //带有特殊的请求头及参数
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                myRequest.Method = "POST";
                byte[] byte1 = GetParms(boundary, Encoding.GetEncoding("utf-8"), datas);
                myRequest.ContentLength = byte1.Length;
                myRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                using (Stream newStream = myRequest.GetRequestStream())
                {
                    newStream.Write(byte1, 0, byte1.Length);
                    newStream.Close();
                }
                content = HttpRequestHelper.getContent(myRequest, Encoding.GetEncoding("utf-8"));
                return content;
            }
            catch (Exception ee)
            {
                return "{ \"time_used\": 3,	\"error_message\": \"获取face信息失败\"}";
            }
        }

        /// <summary>
        /// 删除一个FaceSet集合
        /// </summary>
        /// <param name="faceset_token"></param>
        /// <returns></returns>
        public static string DeleteFaceSet(string faceset_token)
        {
            try
            {
                string content = string.Empty;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://api-cn.faceplusplus.com/facepp/v3/faceset/delete");
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36";
                myRequest.Method = "POST";
                myRequest.ContentLength = 0;

                Dictionary<string, string> datas = new Dictionary<string, string>();
                datas.Add("api_key", api_key);
                datas.Add("api_secret", api_secret);
                datas.Add("faceset_token", faceset_token);
                datas.Add("check_empty", "0");
                //带有特殊的请求头及参数
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                myRequest.Method = "POST";
                byte[] byte1 = GetParms(boundary, Encoding.GetEncoding("utf-8"), datas);
                myRequest.ContentLength = byte1.Length;
                myRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                using (Stream newStream = myRequest.GetRequestStream())
                {
                    newStream.Write(byte1, 0, byte1.Length);
                    newStream.Close();
                }
                content = HttpRequestHelper.getContent(myRequest, Encoding.GetEncoding("utf-8"));
                return content;
            }
            catch (Exception ee)
            {
                return "{ \"time_used\": 3,	\"error_message\": \"获取face信息失败\"}";
            }
        }

        /// <summary>
        /// 查询一个FaceSet集合下的face_token
        /// </summary>
        /// <param name="faceset_token"></param>
        /// <param name="start"></param>
        /// <returns></returns>
        public static string GetFaceSetDetail(string faceset_token, int start)
        {
            try
            {
                string content = string.Empty;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://api-cn.faceplusplus.com/facepp/v3/faceset/getdetail");
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36";
                myRequest.Method = "POST";
                myRequest.ContentLength = 0;

                Dictionary<string, string> datas = new Dictionary<string, string>();
                datas.Add("api_key", api_key);
                datas.Add("api_secret", api_secret);
                datas.Add("faceset_token", faceset_token);
                //带有特殊的请求头及参数
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                myRequest.Method = "POST";
                byte[] byte1 = GetParms(boundary, Encoding.GetEncoding("utf-8"), datas);
                myRequest.ContentLength = byte1.Length;
                myRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                using (Stream newStream = myRequest.GetRequestStream())
                {
                    newStream.Write(byte1, 0, byte1.Length);
                    newStream.Close();
                }
                content = HttpRequestHelper.getContent(myRequest, Encoding.GetEncoding("utf-8"));
                return content;
            }
            catch (Exception ee)
            {
                return "{ \"time_used\": 3,	\"error_message\": \"获取face信息失败\"}";
            }
        }

        /// <summary>
        /// 添加一个face_token在集合faceset中
        /// </summary>
        /// <param name="faceset_token">faceset集合的token</param>
        /// <param name="face_tokens">在识别图片之后，返回的token值</param>
        /// <returns></returns>
        public static string AddFace_Token(string faceset_token, string face_tokens)
        {
            try
            {
                string content = string.Empty;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://api-cn.faceplusplus.com/facepp/v3/faceset/addface");
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36";
                myRequest.Method = "POST";
                myRequest.ContentLength = 0;

                Dictionary<string, string> datas = new Dictionary<string, string>();
                datas.Add("api_key", api_key);
                datas.Add("api_secret", api_secret);
                datas.Add("faceset_token", faceset_token);
                datas.Add("face_tokens", face_tokens);
                //带有特殊的请求头及参数
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                myRequest.Method = "POST";
                byte[] byte1 = GetParms(boundary, Encoding.GetEncoding("utf-8"), datas);
                myRequest.ContentLength = byte1.Length;
                myRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                using (Stream newStream = myRequest.GetRequestStream())
                {
                    newStream.Write(byte1, 0, byte1.Length);
                    newStream.Close();
                }
                content = HttpRequestHelper.getContent(myRequest, Encoding.GetEncoding("utf-8"));
                return content;
            }
            catch (Exception ee)
            {
                return "{ \"time_used\": 3,	\"error_message\": \"获取face信息失败\"}";
            }
        }

        /// <summary>
        /// 删除一个或多个face_token
        /// </summary>
        /// <param name="faceset_token">faceset集合的token</param>
        /// <param name="face_tokens">在识别图片之后，返回的token值</param>
        /// <returns></returns>
        public static string DeleteFace_Token(string faceset_token, string face_tokens)
        {
            try
            {
                string content = string.Empty;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://api-cn.faceplusplus.com/facepp/v3/faceset/removeface");
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36";
                myRequest.Method = "POST";
                myRequest.ContentLength = 0;

                Dictionary<string, string> datas = new Dictionary<string, string>();
                datas.Add("api_key", api_key);
                datas.Add("api_secret", api_secret);
                datas.Add("faceset_token", faceset_token);
                datas.Add("face_tokens", face_tokens);
                //带有特殊的请求头及参数
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                myRequest.Method = "POST";
                byte[] byte1 = GetParms(boundary, Encoding.GetEncoding("utf-8"), datas);
                myRequest.ContentLength = byte1.Length;
                myRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                using (Stream newStream = myRequest.GetRequestStream())
                {
                    newStream.Write(byte1, 0, byte1.Length);
                    newStream.Close();
                }
                content = HttpRequestHelper.getContent(myRequest, Encoding.GetEncoding("utf-8"));
                return content;
            }
            catch (Exception ee)
            {
                return "{ \"time_used\": 3,	\"error_message\": \"获取face信息失败\"}";
            }
        }

        static byte[] GetParms(string boundary, Encoding encoding, Dictionary<string, string> kvs)
        {
            var memStream = new MemoryStream();

            // 边界符  
            //var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary);
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
            var br = Encoding.ASCII.GetBytes("\r\n");

            #region 加入文件

            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(br, 0, br.Length);
            #endregion

            // Key-Value数据  
            var stringKeyHeader = "Content-Disposition: form-data; name=\"{0}\"" +
                                   "\r\n\r\n{1}";
            foreach (byte[] formitembytes in from string key in kvs.Keys
                                             select string.Format(stringKeyHeader, key, kvs[key])
                                                 into formitem
                                             select encoding.GetBytes(formitem))
            {
                memStream.Write(beginBoundary, 0, beginBoundary.Length);
                memStream.Write(br, 0, br.Length);
                memStream.Write(formitembytes, 0, formitembytes.Length);
                memStream.Write(br, 0, br.Length);
            }

            // 写入最后的结束边界符  
            memStream.Write(endBoundary, 0, endBoundary.Length);

            //到tempBuffer
            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            return tempBuffer;
        }

    }
}